package com.example.demo;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/header")
public class HeaderController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //TODO 要注意空指针异常的处理
        if(cookies == null) {
            System.out.println("找不到cookie");
            return "没有cookie";
        }
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("ljd") String value){
        return "获取到ljd的值为: " + value;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        //如果是false, 直接返回null, 默认是true, 没有创建会话返回一个会话
        HttpSession session = request.getSession();
        session.setAttribute("userName","laodi");
        session.setAttribute("age",18);
        return "设置session成功了";
    }

    //第一种获取Session的方法
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        //服务器没有找到Session, 创建一个SessionId返回给客户端
        HttpSession session = request.getSession();
        String userName = (String)session.getAttribute("userName");
        if (userName == null){
            return "未知用户";
        }
        return "从session中获取信息 userName: " + userName;
    }

    //第二种获取Session的方法
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        //服务器没有找到Session, 创建一个SessionId返回给客户端
        String userName = (String) session.getAttribute("userName");
        return "从session2中获取信息 userName: " + userName;
    }

    //第三种获取Session的方法
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userName") String userName){
        return "Session3获取到了userName: " + userName;
    }

    //获取header的方式1, 传统的利用servlet
    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request){
        String userAgent = request.getHeader("user-Agent");
        return "获取到的userAgent: " + userAgent;
    }

    //获取到header的方式二
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("user-Agent") String userAgent){
        return "获取到的userAgent: " + userAgent;
    }
}
